import {
  ref,
  Ref,
  unref,
  watch,
  computed,
  reactive,
  UnwrapNestedRefs,
} from "vue";

import useFetch, { TUseFetchOptions } from "./useFetch";
import { TRequestOptins } from "@/utils/request";

type TUsePageOptions = {
  search?: object | Ref<object>;
  initialData?: any[];

  page?: number;
  size?: number;
  refreshDeps?: any;
} & Omit<TUseFetchOptions, "initialData"> & {};

export default <TData>(
  url: string | Ref<string>,
  options?: TUsePageOptions,
  requeseOptins?: TRequestOptins
) => {
  const list = ref<TData[]>(options?.initialData || []);

  const pages = reactive({
    page: options?.page || 1,
    size: options?.size || 20,
  });

  const { data, loading, error, run } = useFetch<{
    list: TData[];
    total: number;
    last_page?: number;
    total_page: number;
    current_page: number;
  }>(
    url,
    {
      ...options,
      initialData: {
        list: options?.initialData || [],
        total: 0,
        total_page: 0,
        current_page: 1,
      },

      defaultParams: { ...pages, ...unref(options?.search) },

      onSuccess(res) {
        list.value = res.list as UnwrapNestedRefs<TData[]>;
        options?.onSuccess?.(res);
      },
    },
    requeseOptins
  );

  const isAll = computed(
    () => (data.value?.current_page || 0) >= (data.value?.last_page || 0)
  );

  const nextPage = () => {
    if (loading.value || isAll.value) return;
    if (!error.value) {
      pages.page += 1;
    }

    run({ ...pages, ...unref(options?.search) });
  };

  // 恢复到第一页
  const resetToFirst = () => {
    pages.page = 1;
    run({ ...pages, ...unref(options?.search) });
  };

  watch(options?.refreshDeps, () => resetToFirst());

  return {
    list,
    data,
    loading,
    error,
    isAll,
    run,
    nextPage,
    resetToFirst,
  };
};
